package com.hmall.trade.listener;

import com.hmall.api.client.pay.PayClient;
import com.hmall.common.constants.MqConstants;
import com.hmall.trade.domain.po.Order;
import com.hmall.trade.service.IOrderService;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author 16701
 */
@Component
public class CancelOrderListener {
    @Autowired
    private IOrderService orderService;
    @Autowired
    private PayClient payClient;


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConstants.CANCEL_ORDER_QUEUE),
            exchange = @Exchange(value = MqConstants.DELAY_CANCEL_ORDER_EXCHANGE,delayed = "true",type= ExchangeTypes.DIRECT),
            key = MqConstants.CANCEL_ORDER_KEY
    ))
    public void cancelOrderListener(Long orderId){
        // 1.查询订单
        Order order = orderService.getById(orderId);
        // 2.检测订单状态，判断是否0未支付
        if (order == null || order.getStatus() != 1) {
            // 订单不存在或者不是“未支付”状态 已经处理过的，就直接结束（幂等性校验）
            return;
        }
        // 3.订单状态是未支付，需要查询支付单状态（pay服务里pay_order表的支付单状态）
            //远程调用
        Integer status = payClient.getStatusByOrderId(orderId);

        // 4.判断支付单是否已支付
        if(status==3){
            //   如果已支付，标记订单状态为“已支付待发货”
            orderService.markOrderPaySuccess(orderId);
        }else{
            //   否则取消订单，回滚库存(查询订单里都有哪些商品，每个商品买了几个)
            orderService.cancelOrder(5,orderId);

        }
    }
}
